﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using CodeFirstDomain.Model;
using Framework.Infrastructure.Context;

namespace CodeFirstDomain.ModelContext
{
    class CodeFirstContext : MSDbContext
    {

        public CodeFirstContext() : base("CodeFirstSample") { }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>()
             .ToTable("Users");

            modelBuilder.ComplexType<Address>().Property(a => a.Street).HasColumnName("Street").HasColumnType("nvarchar").HasMaxLength(100);

            modelBuilder.Entity<User>()
                .HasMany(u => u.MBlogs).WithRequired().Map(c =>
                {
                    c.MapKey("UserID");
                });
                //.WithRequired(m => m.Author)
                //.WillCascadeOnDelete(true);

            var accountEntiy = modelBuilder.Entity<Account>();

            accountEntiy.HasMany(a => a.Friends).WithMany().Map(fr =>
            {
                fr.ToTable("FriendRelations");
                fr.MapLeftKey("OwnerID");
                fr.MapRightKey("FriendID");
            });


            modelBuilder.Entity<AttentionRelation>().ToTable("AttentionRelations");
            modelBuilder.Entity<AttentionRelation>().HasRequired(ar => ar.Attention).WithMany().WillCascadeOnDelete(false);
            modelBuilder.Entity<AttentionRelation>().HasRequired(ar => ar.Fan).WithMany().WillCascadeOnDelete(false);
            
            modelBuilder.Entity<Loan>().ToTable("Loans");
            modelBuilder.Entity<Loan>().HasOptional(l => l.Shares).WithOptionalPrincipal().WillCascadeOnDelete(true);
            modelBuilder.Entity<SharePie>().ToTable("SharePies");
            modelBuilder.Entity<SharePie>().HasMany(sp => sp.Shares).WithOptional().WillCascadeOnDelete(true);
            base.OnModelCreating(modelBuilder);

        }
    }
}
